package com.wisenet.controller.client;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.annotation.LoginValidate;
import com.wisenet.controller.PlatformController;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 文件上传控制类
 * @author fzh
 */
@RestController
@RequestMapping("/file")
public class UploadController extends PlatformController {
	// 日志
	public static Logger logger = Logger.getLogger(UploadController.class);

	@Value("${img_url}")
	private String imgUrl;
	@Value("${uploadDir}")
	private String uploadDir;

	/**
	 * 上传图片
	 * @param myimage
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/ossUpload", method = RequestMethod.POST)
	public JSONObject ossUpload(MultipartFile myimage) {
		JSONObject jsonObject = getJsonResult(myimage);
		if (jsonObject.getBoolean(SUCCESS)) {
			try {
				String fileName = Math.abs(myimage.getOriginalFilename().hashCode()) + ".jpg";
				File dest = new File(uploadDir + fileName);
				myimage.transferTo(dest);
				jsonObject.put("url", imgUrl + fileName);
			} catch (Exception e) {
				logger.error("保存失败：" + e.getMessage());
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "上传失败");
			}
		}
		return jsonObject;
	}
	
	@Override
	protected String getBasePath() {
		return null;
	}

}
